/*
@Time : 2021/2/23 15:07
@Author : 吴周海
@Mail: wzh200x@126.com
@File : timerTask.go
@Software: GoLand
*/
package function

import (
	"GameApiServer/models"
	"context"
	"github.com/beego/beego/v2/core/logs"
	"sync"
)

var NoSuccessPayOrder []*models.PayRecordInfo //需要补单的数据

var mutex sync.RWMutex // 补单数据读写锁

// 设置补单数组
func SetNoSuccessPayOrders(pInfos []*models.PayRecordInfo) {
	mutex.Lock()
	defer mutex.Unlock()
	NoSuccessPayOrder = pInfos
}

// 增加需要补单的数据
func AddNoSuccessPayOrder(pInfo *models.PayRecordInfo) {
	mutex.Lock()
	defer mutex.RLocker()
	NoSuccessPayOrder = append(NoSuccessPayOrder, pInfo)
}

// 每5分钟执行补单操作
func TaskPayNoSuccessFiveMin(ctx context.Context) error {
	logs.Debug("TaskPayNoSuccessFiveMin run...........")
	mutex.RLock()
	defer mutex.RUnlock()
	var NoSuccessPayOrderTemp []*models.PayRecordInfo
	for i := 0; i < len(NoSuccessPayOrder); i++ {
		// 去充值
		isOK := NoticeServerPay(NoSuccessPayOrder[i])
		if isOK { // 充值成功
			// 修改状态
			NoSuccessPayOrder[i].UpdatePayStatus()
		} else { //充值失败
			// 增加失败的次数
			NoSuccessPayOrder[i].RepeatNotice += 1
			// 存储到数据库
			NoSuccessPayOrder[i].Update()
			// 重试了5次的,不再处理,等待客服去手动搞
			if NoSuccessPayOrder[i].RepeatNotice < 5 {
				// 添加到新列表,以便下次处理
				NoSuccessPayOrderTemp = append(NoSuccessPayOrderTemp, NoSuccessPayOrder[i])
			}
		}
	}
	NoSuccessPayOrder = NoSuccessPayOrderTemp
	return nil
}
